package com.sinbader.xiaole.common.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.modular.enums.UserTypes;
import com.alibaba.fastjson.JSON;
import com.sinbader.xiaole.common.entity.*;
import com.sinbader.xiaole.common.enums.NumberUtilEnum;
import com.sinbader.xiaole.common.enums.Status_;
import com.sinbader.xiaole.common.mapper.ProductWarningMessageMapper;
import com.sinbader.xiaole.common.model.params.ProductWarningMessageParam;
import com.sinbader.xiaole.common.model.result.ProductWarningInfoResult;
import com.sinbader.xiaole.common.model.result.ProductWarningMessageResult;
import com.sinbader.xiaole.common.service.BuyOrderInfoDetailService;
import com.sinbader.xiaole.common.service.BuyOrderInfoService;
import com.sinbader.xiaole.common.service.ProductWarningInfoService;
import  com.sinbader.xiaole.common.service.ProductWarningMessageService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinbader.xiaole.common.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

/**
 * 商品预警消息表 服务实现类
 */
@Service
public class ProductWarningMessageServiceImpl extends ServiceImpl<ProductWarningMessageMapper, ProductWarningMessage> implements ProductWarningMessageService {

    private static final Logger logger = LoggerFactory.getLogger(WarehouseMoveServiceImpl.class);


    @Autowired
    ProductWarningInfoService productWarningInfoService;

    @Autowired
    ProductServiceImpl productService;

    @Autowired
    BuyOrderInfoService buyOrderInfoService;

    @Autowired
    BuyOrderInfoDetailService buyOrderInfoDetailService;


    @Override
    public void add(ProductWarningMessageParam param){
        ProductWarningMessage entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(ProductWarningMessageParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(ProductWarningMessageParam param){
        ProductWarningMessage oldEntity = getOldEntity(param);
        ProductWarningMessage newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public ProductWarningMessageResult findBySpec(ProductWarningMessageParam param){
        return null;
    }

    @Override
    public List<ProductWarningMessageResult> findListBySpec(ProductWarningMessageParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(ProductWarningMessageParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }


    private Serializable getKey(ProductWarningMessageParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private ProductWarningMessage getOldEntity(ProductWarningMessageParam param) {
        return this.getById(getKey(param));
    }

    private ProductWarningMessage getEntity(ProductWarningMessageParam param) {
        ProductWarningMessage entity = new ProductWarningMessage();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }



    @Override
    public void saveProductWarningMessage(Long orgId, String type, String orgName, Long productId, Integer warehouseUsableCount) {

        Map<String,Object> paramMap = new HashMap();
        paramMap.put("type",type);
        paramMap.put("orgId",orgId);
        paramMap.put("productId",productId);
        ProductWarningInfoResult productWarningInfoByMap = productWarningInfoService.getProductWarningInfoByMap(paramMap);
//        logger.info("",);
        if (productWarningInfoByMap != null && productWarningInfoByMap.getId() != null){
            logger.info("productWarningInfo:",productWarningInfoByMap);
            ProductWarningMessage productWarningMessage = new ProductWarningMessage();
            productWarningMessage.setType(type);
            productWarningMessage.setOrgId(orgId);
            productWarningMessage.setOrgName(orgName);
            productWarningMessage.setProductName(productWarningInfoByMap.getProductName());
            productWarningMessage.setProductId(productId);
//            productWarningMessage.setCountType(productWarningInfoByMap.getCountType());
            productWarningMessage.setLessWarningValue(productWarningInfoByMap.getLessWarningValue());
            productWarningMessage.setSendAmount(productWarningInfoByMap.getSendAmount());
            productWarningMessage.setWarehouseUsableCount(warehouseUsableCount);
            productWarningMessage.setCreateTime(new Date());
            //0:未发货
            productWarningMessage.setStatus(0);
            logger.info(type+"生成预警消息列表:{}",productWarningMessage);
            this.save(productWarningMessage);
        }
    }

    /**
     *
     * @param ids
     */
    @Override
    public void sendProduct(List<Long> ids,String userType) {
        logger.info("发货项数：｛｝",ids.size());
        if (ids != null && ids.size() > 0){

           if (userType.equals(UserTypes.Supplier)){
               //供应商发货生成采购订单
               this.supplierSendProduct(ids);

           }else if(userType.equals(UserTypes.Group)){
               //总部发货生成调拨出库单
               this.groupSendProduct(ids);

            }
        }
        logger.info("发货结束！！！");
    }


    //供应商发货生成采购订单
    private void supplierSendProduct(List<Long> ids) {
        logger.info("供应商发货生成采购订单开始！！！！");

        Long supplierId = 0L;
        String supplierName = "";
        Integer orderTotalCount = 0;
        BigDecimal orderTotalAmt = new BigDecimal(BigInteger.ZERO);
        List<BuyOrderInfoDetail> listDetail = new ArrayList<>();
        for (Long id : ids){

          ProductWarningMessage productWarningMessage = this.getById(id);
          if (productWarningMessage != null && productWarningMessage.getId() != null && productWarningMessage.getType().equals(UserTypes.Supplier)){
              supplierId = productWarningMessage.getOrgId();
              supplierName = productWarningMessage.getOrgName();
              Map paramMap = new HashMap();
              paramMap.put("orgId",productWarningMessage.getOrgId());
              paramMap.put("type",productWarningMessage.getType());
              paramMap.put("productId",productWarningMessage.getProductId());

              ProductWarningInfoResult productWarningInfoByMap = productWarningInfoService.getProductWarningInfoByMap(paramMap);
              Product product = productService.getById(productWarningMessage.getProductId());

              logger.info("该供应商发货数量：｛｝",productWarningInfoByMap.getSendAmount());
              orderTotalCount =  orderTotalCount + productWarningInfoByMap.getSendAmount();
              orderTotalAmt = orderTotalAmt.add(product.getPurchasePrice());

              BuyOrderInfoDetail detail = new BuyOrderInfoDetail();
//              listDetail
//              logger.info("");
//              detail.setDetailNum(NumberUtilEnum.采购订单.getName());
              detail.setProductId(product.getId());
              detail.setProductName(product.getProductName());
              detail.setSupplierId(product.getSupplierId());
              detail.setSupplierName(product.getSupplierName());
              detail.setOrderCount(productWarningInfoByMap.getSendAmount());
              detail.setUnitPrice(product.getPurchasePrice());
              detail.setOrderAmt(product.getPurchasePrice());
              detail.setOrderTypeCount(1);
              detail.setCreateTime(new Date());
              detail.setStatus(Status_.OrderStatus.no.getId());
              listDetail.add(detail);

          }else {
              logger.info("该预警消息不符合生成采购订单条件：｛｝", productWarningMessage);
              continue;
          }

        }

        if (orderTotalCount > 0 ){

            String orderNum = StringUtil.getIDNumber(NumberUtilEnum.采购订单.getName());
            BuyOrderInfo buyOrderInfo = new BuyOrderInfo();
            buyOrderInfo.setOrderNum(orderNum);

            buyOrderInfo.setSupplierId(supplierId);
            buyOrderInfo.setSupplierName(supplierName);

            buyOrderInfo.setOrderTotalCount(orderTotalCount);
            buyOrderInfo.setOrderTotalAmt(orderTotalAmt);

            buyOrderInfo.setInStockStatus(Status_.InStockStatus.no.getId());
            buyOrderInfo.setBuyOrderDate(new Date());
            buyOrderInfo.setOrderTypeCount(ids.size());
            buyOrderInfo.setCreateTime(new Date());
            buyOrderInfo.setStatus(Status_.OrderStatus.no.getId());
            buyOrderInfoService.save(buyOrderInfo);
            logger.info("生成采购订单：｛｝",buyOrderInfo);
            for (BuyOrderInfoDetail detail : listDetail){
                detail.setParentId(buyOrderInfo.getId());
                buyOrderInfoDetailService.save(detail);
            }
        }


    }
    //总部发货生成调拨出库单
    private void groupSendProduct(List<Long> ids) {
    }




}
